import { searchProps } from './props/crudProps'
import { ElButton, ElForm, ElFormItem } from 'element-plus'
import { PropType } from 'vue'
import { IColumn } from '@/components/common/types/tableCommon'
import { componentMap, renderOptions } from '@/components/common/render/useRenderComponent'
import { useI18n } from 'vue-i18n'

export default defineComponent({
  name: 'YtTableSearch',
  props: {
    column: {
      type: Array as PropType<IColumn[]>,
      default: () => [],
    },
    ...searchProps,
  },
  emits: ['handleSearch', 'update:query'],
  setup(props, { slots, emit }) {
    const { t, locale } = useI18n()
    // 表单数据
    const formModel = ref<Recordable>(props.query)
    const getAttr = (option: IColumn) => {
      return {
        clearable: props.clearable,
        placeholder: `${option.type === 'string' || !option.type ? t('crud.search.pleaseInput') : t('crud.search.pleaseSelect')}${option.label}`,
        ...option.componentProps,
      }
    }
    const queryFormRef = ref()

    // watch(
    //   () => formModel,
    //   (newV) => {
    //     emit('update:query', newV.value || {})
    //   },
    //   {
    //     immediate: true,
    //     deep: true,
    //   }
    // )

    const searchData = ref<IColumn[]>([])

    if (props.showKeyword) {
      const keywordColumn: IColumn = {
        label: t('crud.table.column.keyword'),
        key: 'keyword',
        align: 'center',
        search: true,
        hide: true,
        sortable: false,
        formHide: true,
        searchSlot: false,
        componentProps: {
          placeholder: props.keywordPlaceholder || undefined,
          style: {
            width: props.keywordWidth + 'px',
          },
        },
      }
      searchData.value.push(keywordColumn)
    }

    props.column.forEach((item: IColumn) => {
      if (item.search) {
        searchData.value.push(item)
      }
    })

    const handleQuery = () => {
      const queryData = Object.assign({}, formModel.value)
      searchData.value.map((m: IColumn) => {
        if (m.type == 'i18nString') {
          const text = queryData[m.key]
          if (text) {
            queryData[m.key] = {}
            queryData[m.key][locale.value] = text
          } else {
            queryData[m.key] = null
          }
        }
      })

      emit('handleSearch', queryData)
    }

    const resetQuery = () => {
      queryFormRef.value.resetFields()
      handleQuery()
    }

    return () => {
      return (
        searchData.value?.length > 0 && (
          <div class="search">
            <ElForm ref={queryFormRef} inline={true} labelWidth={props.labelWidth} model={formModel}>
              {searchData.value.map((m: IColumn) => {
                let type = m?.type || 'string'
                if (type == 'i18nString') {
                  type = 'string'
                }
                const Com = componentMap.get(type) as ReturnType<typeof defineComponent>

                return (
                  <ElFormItem
                    label-width={m.searchLabelWidth}
                    label={m.label + ':'}
                    prop={m.key}
                    style={{
                      marginBottom: 0,
                    }}
                  >
                    {!m.searchSlot ? (
                      <Com v-model={formModel.value[m.key]} {...getAttr(m)}>
                        {renderOptions(m)}
                      </Com>
                    ) : (
                      slots[m.key + 'Search']?.({
                        column: m,
                        row: formModel.value,
                      })
                    )}
                  </ElFormItem>
                )
              })}
              <ElButton
                type="primary"
                onClick={handleQuery}
                icon="Search"
                style={{
                  padding: '8px 12px 8px 8px',
                }}
                loading={props.loading}
              >
                {t('crud.searchText')}
              </ElButton>
              <ElButton
                onClick={resetQuery}
                style={{
                  padding: '8px 12px 8px 8px',
                }}
                icon="Refresh"
              >
                {t('crud.resetText')}
              </ElButton>
            </ElForm>
          </div>
        )
      )
    }
  },
})
